package apis

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"gorm.io/gorm"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
	"tuowei.com/pkg/xlog"
)

type SysFinanceTxmx struct {
	api.Api
}

// GetPage
// @Summary 列表提现明细数据
// @Description 获取JSON
// @Tags 提现明细
// @Param username query string false "username"
// @Success 200 {string} {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-finance-txmx [get]
// @Security Bearer
func (e SysFinanceTxmx) GetPages(c *gin.Context) {
	s := service.SysFinanceTxmx{}
	req := dto.SysFinanceTxmxGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Default(c.Request.Method, c.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]models.SysFinanceTxmx, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
func (e SysFinanceTxmx) GetPagesByAccount(c *gin.Context) {
	s := service.SysFinanceTxmx{}
	req := dto.SysFinanceTxmxGetPageByAccountReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	xlog.Info("GetPagesByAccount req:%+v", req)
	txmxReq := models.SysFinanceTxmx{}
	err = s.GetById(req.FinanceTxmxId, &txmxReq)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	type TxmxAccountResp struct {
		AccountInfo       interface{}             `json:"account_info"`
		ClassInfo         models.SysClass         `json:"class_info"`
		FinanceTxmxDetail models.SysFinanceTxmx   `json:"finance_txmx_detail"`
		Lists             []models.SysFinanceTxmx `json:"lists"`
	}
	txmxAccountResp := TxmxAccountResp{}
	txmxAccountResp.FinanceTxmxDetail = txmxReq

	//组装获取list req
	pageReq := dto.FinanceTxmxGetPage{}
	pageReq.PageIndex = req.PageIndex
	pageReq.PageSize = req.PageSize
	pageReq.Account = txmxReq.Account
	pageReq.UserType = txmxReq.UserType
	list := make([]models.SysFinanceTxmx, 0)
	var count int64

	err = s.GetPageByName(&pageReq, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	txmxAccountResp.Lists = list
	switch txmxReq.UserType {
	case "网课教师":
		var data models.SysLecturer
		err := e.Orm.Debug().
			Scopes(
				actions.Permission(data.TableName(), p),
			).Where("user_id = ?", txmxReq.Account).
			First(&data).Error

		if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
			xlog.Errorf("db error: %s", err)
			e.Error(500, err, err.Error())
			return
		}
		txmxAccountResp.AccountInfo = data
	case "线上学生", "线下学生":
		var data models.SysStudent
		err := e.Orm.Debug().
			Scopes(
				actions.Permission(data.TableName(), p),
			).Where("phone = ?", txmxReq.Account).
			First(&data).Error

		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				e.OK(nil, err.Error())
				return
			}
			xlog.Errorf("db error: %s", err)
			e.Error(500, err, err.Error())
			return
		}
		txmxAccountResp.AccountInfo = data
		var dataClass models.SysClass
		if data.ClassId != 0 {
			err = e.Orm.Debug().
				Scopes(
					actions.Permission(dataClass.TableName(), p),
				).Where("id = ?", data.ClassId).
				First(&dataClass).Error

			if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
				xlog.Errorf("db error: %s", err)
				e.Error(500, err, err.Error())
				return
			}
		}
		txmxAccountResp.ClassInfo = dataClass
	}

	e.PageOK(txmxAccountResp, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Insert
// @Summary 添加提现明细
// @Description 获取JSON
// @Tags 提现明细
// @Accept  application/json
// @Product application/json
// @Param data body dto.SysConsultLBTInsertReq true "提现明细数据"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-finance-txmx [post]
// @Security Bearer
func (e SysFinanceTxmx) Insert(c *gin.Context) {
	s := service.SysFinanceTxmx{}
	req := dto.SysFinanceTxmxInsertReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.Insert(&req)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	e.OK(req.GetId(), "创建成功")
}

func (e SysFinanceTxmx) Change(c *gin.Context) {
	s := service.SysFinanceTxmx{}
	req := dto.SysFinanceTxmxUpdateReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.Update(&req)
	if err != nil {
		e.Error(500, err, "更新失败")
		return
	}
	e.OK(req.GetId(), "更新成功")
}

// Delete
// @Summary 删除提现明细
// @Description 删除数据
// @Tags 提现明细
// @Param data body dto.SysConsultLBTDeleteReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-consult-lbt [delete]
// @Security Bearer
//func (e SysFinanceTxmx) Delete(c *gin.Context) {
//	s := new(service.SysFinanceTxmx)
//	req := dto.SysFinanceTxmxDeleteReq{}
//	err := e.MakeContext(c).
//		MakeOrm().
//		Bind(&req, binding.JSON).
//		MakeService(&s.Service).
//		Errors
//	if err != nil {
//		e.Logger.Error(err)
//		e.Error(500, err, fmt.Sprintf("删除角色 %v 失败，\r\n失败信息 %s", req.Ids, err.Error()))
//		return
//	}
//
//	err = s.Remove(&req)
//	if err != nil {
//		e.Logger.Error(err)
//		e.Error(500, err, "")
//		return
//	}
//	_, err = global.LoadPolicy(c)
//	if err != nil {
//		e.Error(500, err, fmt.Sprintf("删除角色 %v 失败，失败信息 %s", req.GetId(), err.Error()))
//		return
//	}
//	e.OK(req.GetId(), fmt.Sprintf("删除角色角色 %v 状态成功！", req.GetId()))
//}
